package com.stylefeng.guns.rest.modular.wz.api.v3;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.api.v3.dao.WzAdvMapDao;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzAdvMapService;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.impl.WzAdvMapServiceImpl;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.service.IPfFileService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserInfoService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 周边店铺
 */
@RestController
@RequestMapping("/wz/api/v3/advMap/")
public class WzAdvMapApi extends ApiBaseController {

    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private IWzAdvMapService advMapService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzAdvMapCategoryMapper advMapCategoryMapper;
    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private IWzUserInfoService wzUserInfoService;
    @Autowired
    private WzAdvMapServiceImpl wzAdvMapService;
    @Autowired
    private WzAdvServiceImpl wzAdvService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzAdvMapDao advMapDao;
    @Autowired
    private WzAdvServiceImpl advService;
    @Autowired
    private WzAdvCommentMapper advCommentMapper;
    @Autowired
    private WzRedpacketCommentMapper redpacketCommentMapper;
    @Autowired
    private IWzUserService wzUserService;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private IWzUserInfoService userInfoService;
    @Autowired
    private WzMapActivityMapper mapActivityMapper;
    @Autowired
    private WzAdvMapStaffMapper advMapStaffMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;
    @Autowired
    private WzCouponMapper couponMapper;


    //地图显示完整信息的数量
    public static int advMapShowNumber = 15;
    //红包天数1
    public static int dayNumber = 500;
    public static Long start = 0L;


    /**
     * 主页搜索周边店铺
     */
    @PostMapping("advMapSearch")
    public Res advMapSearch(@RequestBody ParamMap paramMap) {
        //版本判断
        String androidVersion = paramMap.getStrValid("androidVersion");
        String iosVersion = paramMap.getStrValid("iosVersion");
        int ios = 0;
        int android = 0;
        if(StringUtils.isNotBlank(iosVersion)){
            ios = Integer.parseInt(iosVersion.substring(0,1))*100 + Integer.parseInt(iosVersion.substring(2,3))*10 + Integer.parseInt(iosVersion.substring(4,5));
        }
        if(StringUtils.isNotBlank(androidVersion)){
            android = Integer.parseInt(androidVersion);
        }
        if(android > 30 || ios > 150){//新务处理
            Res res = wzAdvMapService.newAdvMapSearch(paramMap);
            return res;
        }else{//旧业务处理
            Res res = wzAdvMapService.advMapSearch(paramMap);
            return res;
        }
    }


    /**
     * 红包领钱
     */
    @PostMapping("repackedReward")
    public Res repackedReward(@RequestBody ParamMap paramMap) {
        String androidVersion = paramMap.getStrValid("androidVersion");
        String iosVersion = paramMap.getStrValid("iosVersion");
        boolean rr = true;
        if(!com.stylefeng.guns.rest.common.util.StringUtils.isBlankStr(iosVersion)){
            int ios = Integer.parseInt(iosVersion.substring(0,1))*100 + Integer.parseInt(iosVersion.substring(2,3))*10 + Integer.parseInt(iosVersion.substring(4,5));
            if(ios >= Integer.parseInt(Consts.iosVersion)){
                rr = false;
            }
        }
        if(!com.stylefeng.guns.rest.common.util.StringUtils.isBlankStr(androidVersion)){
            int a = Integer.parseInt(androidVersion);
            if(a >= Integer.parseInt(Consts.androidVersion)){
                rr = false;
            }
        }
        if(rr){
            return Res.fail("版本太低无法领钱，请更新!");
        }
        String adCode = paramMap.getStrMisValid("adCode");
        Long advMapId = paramMap.getLongMisValid("advMapId");
        WzAdvMap advMap = advMapMapper.selectById(advMapId);
        //位置判断
        if(adCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        boolean f = advService.adCodeCheck(adCode,advMap.getAdCode());
        if(!f){
            return Res.fail("所在地区无法领红包!");
        }
        //业务处理
        Res res = wzAdvMapService.userAdvReward(paramMap,advMap);
        return res;
    }

    /**
     * 全部周边店铺列表
     */
    @PostMapping("list")
    public Res list(@RequestBody ParamMap paramMap) {
        //业务处理
        paramMap = wzAdvMapService.advMapData(paramMap);
        return Res.success(paramMap);
    }

    /**
     * 筛选分类
     */
    @PostMapping("selectCategory")
    public Res selectCategory(@RequestBody ParamMap paramMap){
        //业务处理
        Res res = wzAdvMapService.advMapSelectCategory(paramMap);
        return res;
    }

    /**
     * 我的广告地图列表
     */
    @PostMapping("myList")
    public Res myList(@RequestBody ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        List<Map<String, Object>> advMapList = advMapMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzAdvMap>().eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).eq("user_code", userCode).notIn("status", new Integer[]{EnWzAdvMap.STATUS_Editors.getIndex(), EnWzAdvMap.STATUS_Pass.getIndex(), EnWzAdvMap.STATUS_Delete.getIndex()}));
        for (Map<String, Object> map : advMapList) {
            map.put("advMapDetail", "");
            if (StringUtils.isNotBlank(map.get("targetId").toString())) {
                Long targetId = Long.parseLong(map.get("targetId").toString());
                WzAdvMap targetAdvMap = advMapService.selectById(targetId);
                map.put("name", targetAdvMap.getName());
                map.put("logo",targetAdvMap.getLogo());
                map.put("avatarUrl", targetAdvMap.getAvatarUrl());
                map.put("subtitle", targetAdvMap.getSubtitle());
                map.put("merchantTel", targetAdvMap.getMerchantTel());
                map.put("shareLink", targetAdvMap.getShareLink());
            }
        }
        return Res.success(paramMap.data(advMapList));
    }

    /**
     * 新增周边店铺
     */
    @PostMapping("add")
    public Res add(@RequestBody ParamMap paramMap) throws Exception {
        //业务处理
        Res res = wzAdvMapService.advMapAdd(paramMap);
        return res;
    }

    /**
     * 店铺展示详情
     */
    @PostMapping("showDetail")
    public Res showDetail(@RequestBody ParamMap paramMap) {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        int type = paramMap.getIntValid("type");//类型：1-后台审核
        int isDev;
        if (Consts.dev.equals("true")) {
            isDev=1;
        }else{
            isDev=0;
        }
        String sql = "adv_map_id As advMapId,user_code As userCode,avatar_url As avatarUrl,logo,longitude,latitude,merchant_full_address As merchantFullAddress,merchant_tel As merchantTel,name,subtitle,status,share_link As shareLink,target_id As targetId";
        Map<String, Object> advMap = advMapService.selectMap(new EntityWrapper<WzAdvMap>().setSqlSelect(sql).eq("adv_map_id", advMapId));
        advMap.put("shareLink",advMap.get("shareLink")+"?advMapId="+advMapId+"&showMapMerge=1&isDev="+isDev);
        if (StringUtils.isNotBlank(advMap.get("targetId").toString()) && type == 1) {
            Long targetId = Long.parseLong(advMap.get("targetId").toString());
            WzAdvMap targetAdvMap = advMapService.selectById(targetId);
            advMap.put("name", targetAdvMap.getName());
            advMap.put("avatarUrl", targetAdvMap.getAvatarUrl());
            advMap.put("logo",targetAdvMap.getLogo());
            advMap.put("subtitle", targetAdvMap.getSubtitle());
            advMap.put("merchantTel", targetAdvMap.getMerchantTel());
            advMap.put("shareLink", targetAdvMap.getShareLink()+"?advMapId="+advMapId+"&showMapMerge=1&isDev="+isDev);
            advMap.put("merchantFullAddress", targetAdvMap.getMerchantFullAddress());
            advMap.put("longitude", targetAdvMap.getLongitude());
            advMap.put("latitude", targetAdvMap.getLatitude());
        }
        advMap.remove("targetId");
        //团返利
        String mapRebateSql = "map_rebate_id AS mapRebateId,merchant_name AS merchantName,benefit,rebate_price AS rebatePrice,sales,pic";
        List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMapsPage(new Page<>(1,3),new EntityWrapper<WzMapRebate>().setSqlSelect(mapRebateSql).eq("status", EnWzMapRebate.STATUS_RELEASE.getIndex()).eq("adv_map_id",advMapId).orderBy("create_time"));
        advMap.put("mapRebateList",mapRebateList);

        //拼单
        String mapMergeListSql = "map_merge_id AS mapMergeId,merchant_name AS merchantName,benefit,merge_price AS mergePrice,sales,pic";
        List<Map<String, Object>> mapMergeList = mapMergeMapper.selectMapsPage(new Page<>(1, 3), new EntityWrapper<WzMapMerge>().setSqlSelect(mapMergeListSql).eq("adv_map_id",advMapId).eq("status", EnWzMapMerge.STATUS_RELEASE.getIndex()).orderBy("create_time"));
        advMap.put("mapMergeList",mapMergeList);
        return Res.success(advMap);
    }

    /**
     * 单个周边店铺详情-主页
     */
    @PostMapping("detail")
    public Res detail(@RequestBody ParamMap paramMap) {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        Map<String, Object> advMap = advMapService.selectMap(new EntityWrapper<WzAdvMap>().eq("adv_map_id", advMapId));
        Long userInfoId = Long.parseLong(advMap.get("userInfoId").toString());
        WzUserInfo userInfo = userInfoService.selectById(userInfoId);
        advMap.put("merchantName", userInfo.getMerchantName());
        int isDev;
        if (Consts.dev.equals("true")) {
            isDev=1;
        }else{
            isDev=0;
        }
        advMap.put("shareLink",advMap.get("shareLink")+"?advMapId="+advMapId+"&showMapMerge=1&isDev="+isDev);
        //评论数
        advMap.put("commentNum",  redpacketCommentMapper.selectCount(new EntityWrapper<WzRedpacketComment>().eq("adv_id",advMapId)));
        if (StringUtils.isNotBlank(advMap.get("targetId").toString())) {
            Long targetId = Long.parseLong(advMap.get("targetId").toString());
            WzAdvMap targetAdvMap = advMapService.selectById(targetId);
            advMap.put("name", targetAdvMap.getName());
            advMap.put("avatarUrl", targetAdvMap.getAvatarUrl());
            advMap.put("logo",targetAdvMap.getLogo());
            advMap.put("subtitle", targetAdvMap.getSubtitle());
            advMap.put("merchantTel", targetAdvMap.getMerchantTel());
            advMap.put("shareLink", targetAdvMap.getShareLink()+"?advMapId="+advMapId+"&showMapMerge=1&isDev="+isDev);
            advMap.put("advMapDetail", targetAdvMap.getAdvMapDetail());
//            advMap.put("advMapCategoryFirst", targetAdvMap.getAdvMapCategoryFirst());
//            advMap.put("advMapCategorySecond", targetAdvMap.getAdvMapCategorySecond());
//            advMap.put("advMapCategoryThird", targetAdvMap.getAdvMapCategoryThird());
        }
        String mapActivitySql = "benefit";
        List<Map<String, Object>> mapActivitys = mapActivityMapper.selectMaps(new EntityWrapper<WzMapActivity>().setSqlSelect(mapActivitySql).eq("adv_map_id",advMapId).eq("status",EnWzMapActivity.STATUS_RELEASE.getIndex()).gt("surplus_number",0));
        advMap.put("mapActivitys",mapActivitys);
        return Res.success(advMap);
    }

    /**
     * 删除周边店铺
     */
    @PostMapping("delete")
    public Res deleteAdvMap(@RequestBody ParamMap paramMap) throws Exception {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        WzAdvMap advMap = advMapMapper.selectById(advMapId);
        if(advMap.getStatus() == EnWzAdvMap.STATUS_Add_Reject.getIndex()){
            int r = advMapMapper.deleteById(advMapId);
            if(r > 0){
                List<PfFile> pfFiles = pfFileService.selectList(new EntityWrapper<PfFile>().eq("target_id",advMapId.toString()));
                for(PfFile pfFile:pfFiles){
                    AliOssUtil.deleteObject(pfFile.getFileUrl(), pfFile.getType(), pfFile.getBucketName());
                    pfFileService.deleteById(pfFile.getFileId());
                }
                return Res.success();
            }
        }else if(advMap.getStatus() == EnWzAdvMap.STATUS_Expired.getIndex()){
            advMap.setStatus(EnWzAdvMap.STATUS_Delete.getIndex());
            Integer r = advMapMapper.updateById(advMap);
            if (r > 0) {
                return Res.success();
            }
        }else{
            return Res.fail("当前不可删除!");
        }
        return Res.fail();
    }

    /**
     * 修改周边店铺
     */
    @PostMapping("edit")
    public Res edit(@RequestBody ParamMap paramMap) throws Exception {
        //业务处理
        Res res = wzAdvMapService.advMapEdit(paramMap);
        return res;
    }


    /**
     * 发店铺红包
     */
    @PostMapping("setTopAdvMap")
    public Res stickAdvMap(@RequestBody ParamMap paramMap) throws Exception {
        Res res = wzAdvMapService.setTopAdvMap(paramMap);
        return res;
    }

    /**
     * 周边店铺续费
     */
    @PostMapping("renewalsAdvMap")
    public Res renewalsAdvMap(@RequestBody ParamMap paramMap) throws ParseException {
        Res res = wzAdvMapService.renewalsAdvMap(paramMap);
        return res;
    }

    /**
     * 被驳回后使用原文章
     */
    @PostMapping("usePrevious")
    public Res usePrevious(@RequestBody ParamMap paramMap) throws Exception{
        Long advMapId = paramMap.getLongMisValid("advMapId");
        WzAdvMap advMap = advMapService.selectById(advMapId);
        if(StringUtils.isNotBlank(advMap.getTargetId())){
//            List<PfFile> pfFiles = pfFileService.selectList(new EntityWrapper<PfFile>().eq("target_id",advMap.getTargetId()));
//            for(PfFile pfFile:pfFiles){
//                AliOssUtil.deleteObject(pfFile.getFileUrl(), pfFile.getType(), pfFile.getBucketName());
//                pfFileService.deleteById(pfFile.getFileId());
//            }
            advMapMapper.deleteById(Long.parseLong(advMap.getTargetId()));//删除修改的内容
        }
        advMap.setStatus(EnWzAdvMap.STATUS_Release.getIndex());
        advMap.setTargetId("");
        advMap.setRejectRemark("");
        int r = advMapMapper.updateById(advMap);
        if(r > 0){
            return Res.success();
        }
        return Res.fail();
    }

    /**
     * 店铺员工列表
     */
    @PostMapping("staffList")
    public Res staffList(@RequestBody ParamMap paramMap) {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        List<Map<String, Object>> list = advMapStaffMapper.selectMaps(new EntityWrapper<WzAdvMapStaff>().setSqlSelect("adv_map_staff_id AS advMapStaffId,user_code AS userCode").eq("adv_map_id", advMapId));
        //店长信息
        WzAdvMap advMap=cacheService.advMap(advMapId);
        Map selfMap = new HashMap();
        WzUser self = cacheService.user(advMap.getUserCode());
        String avatarUrl = self.getAvatarUrl();
        if (!avatarUrl.startsWith("http")) {
            avatarUrl = Consts.DOMAIN + avatarUrl;
        }
        selfMap.put("account", self.getAccount());
        selfMap.put("avatarUrl", avatarUrl);
        selfMap.put("nickName", self.getNickName());
        selfMap.put("userCode", advMap.getUserCode());
        selfMap.put("advMapStaffId", "");
        list.add(selfMap);
        for (Map staff : list) {
            WzUser user = cacheService.user(Long.parseLong(staff.get("userCode").toString()));
            avatarUrl = user.getAvatarUrl();
            if (!avatarUrl.startsWith("http")) {
                avatarUrl = Consts.DOMAIN + avatarUrl;
            }
            staff.put("account", user.getAccount());
            staff.put("avatarUrl", avatarUrl);
            staff.put("nickName", user.getNickName());
        }
        return Res.success(list);
    }

    /**
     * 通过手机号搜索用户
     */
    @PostMapping("searchUserByAccount")
    public Res searchUser(@RequestBody ParamMap paramMap) {
        String account = paramMap.getStrMisValid("account");
        Map<String, Object> user = wzUserService.selectMap(new EntityWrapper<WzUser>().setSqlSelect("avatar_url AS avatarUrl,nick_name AS nickName,account,user_code AS userCode").eq("account", account));
        if (user != null) {
            String avatarUrl = user.get("avatarUrl").toString();
            if (!avatarUrl.startsWith("http")) {
                avatarUrl = Consts.DOMAIN + avatarUrl;
                user.put("avatarUrl", avatarUrl);
            }
            return Res.success(user);
        } else {
            return Res.fail("该用户不存在");
        }
    }


    /**
     * 添加店铺员工
     */
    @PostMapping("addStaff")
    public Res addStaff(@RequestBody ParamMap paramMap) {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        Long userCode = paramMap.getLongMisValid("userCode");
        WzAdvMap advMap=cacheService.advMap(advMapId);
        Long code=advMap.getUserCode();
        if(userCode.equals(code)){
            return Res.fail("不能添加自己！");
        }
        WzAdvMapStaff staff = new WzAdvMapStaff();
        staff.setAdvMapId(advMapId);
        staff.setUserCode(userCode);
        staff.setCreateTime(new Date());
        int count = advMapStaffMapper.selectCount(new EntityWrapper<WzAdvMapStaff>().eq("adv_map_id", advMapId).eq("user_code", userCode));
        if (count > 0) {
            return Res.fail("该用户已添加！");
        } else {
            boolean b = staff.insert();
            if (b) {
                return Res.success();
            }
        }
        return Res.fail();
    }


    /**
     * 删除店铺员工
     */
    @PostMapping("delStaff")
    public Res delStaff(@RequestBody ParamMap paramMap) {
        Long advMapStaffId = paramMap.getLongMisValid("advMapStaffId");
        WzAdvMapStaff staff=advMapStaffMapper.selectById(advMapStaffId);
        Long advMapId=staff.getAdvMapId();
        WzAdvMap advMap=cacheService.advMap(advMapId);
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        Long userCodes=advMap.getUserCode();
        if(!userCode.equals(userCodes)){
            return Res.fail("无法删除！");
        }
        int r = advMapStaffMapper.deleteById(advMapStaffId);
        if (r > 0) {
            return Res.success();
        }
        return Res.fail();
    }
}
